<script lang="ts" setup>
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { insertLife, updateLife } from '#/api';
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'title',
      label: '标题',
      rules: 'required',
    },
    {
      component: 'Textarea',
      fieldName: 'content',
      label: '内容',
      rules: 'required',
    },
    {
      component: 'DatePicker',
      fieldName: 'date',
      componentProps: {
        placeholder: '请选择日期',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD',
      },
      label: '日期',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'location',
      label: '地点',
    },
    {
      component: 'Input',
      fieldName: 'people',
      label: '人物',
    },
    {
      component: 'Input',
      fieldName: 'categories',
      label: '分类',
    },
  ],
  wrapperClass: 'grid-cols-1',
});
let isAdd = true;
let id = '';
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/2',
  onConfirm: getValue,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      formApi.resetForm();
      const { isEdit, ...values } = drawerApi.getData();
      isAdd = !isEdit;
      if (isEdit) {
        id = values.id;
        formApi.setValues(values);
      }
      console.log(isAdd);
    }
  },
});
async function getValue() {
  const validate = await formApi.validate();
  if (validate?.valid) {
    const data = await formApi.getValues();
    if (isAdd) {
      insertLife(data).then((r) => {
        drawerApi.close();
      });
    } else {
      updateLife({ id, ...data }).then((r) => {
        drawerApi.close();
      });
    }

    return data;
  }
}
</script>
<template>
  <Drawer title="新增" @onConfirm="getValue"> <BaseForm /> </Drawer>
</template>
